//https://www.npmjs.com/package/connect
//Connect is an extensible HTTP server framework for node using "plugins" known as middleware.
//Connect是一个框架，它使用被称为中间件的模块化组件，以可重用的方式实现web程序的逻辑
//在Connect中，中间件组件是一个函数，它拦截HTTP服务器提供的请求和响应，执行逻辑，然后，或者结束响应，或者把它传递给下一个中间件组件
//一个非常老的node服务器，Express就是构建在Connect之上的更高层的框架
const connect = require('connect');
const http = require('http');
const serveStaticMiddleware = require('./middlewares/serveStaticMiddleware');
const resolveConfig = require('../config');
const {createOptimizeDepsRun} = require('../optimizer');

async function createServer() {
  const config = await resolveConfig();
  const middlewares = connect();

  const server = {
    async listen(port){

      await runOptimize(config);

      http.createServer(middlewares).listen(port,async ()=>{
        console.log(`server running at http://localhost:${port}`);
      })
    }
  }

  middlewares.use(serveStaticMiddleware(config));

  return server;
}

async function runOptimize(config){
  await createOptimizeDepsRun(config);
}

exports.createServer = createServer;
